import 'dart:io';

import 'package:enjoy_plus_flutter_7/eventBus/event_bus.dart';
import 'package:enjoy_plus_flutter_7/utils/TokenManager.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import '../../api/login.dart';

class MinePage extends StatefulWidget {
  const MinePage({Key? key, required this.activeIndex, required this.toIndex})
      : super(key: key);
  final int activeIndex;
  final Function(int) toIndex;
  @override
  _MinePageState createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  Map<String, dynamic> userInfo = {'avatar': '', 'nickName': '', 'id': ''};
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    event_bus.on<LogSccessEvent>().listen((event) {
      getUserInfo();
    });
  }

  @override
  void didUpdateWidget(covariant MinePage oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    print(widget.activeIndex);
    if (widget.activeIndex == 1) {
      getUserInfo();
    }
    print(userInfo);
  }

  getUserInfo() async {
    userInfo = await userInfoAPI();

    setState(() {});

    // print(res);
  }

  Widget getImg() {
    if ((userInfo['avatar'] == null &&
            userInfo['nickName'] == null &&
            userInfo['id'] == null) ||
        (userInfo['avatar'] == '' &&
            userInfo['nickName'] == '' &&
            userInfo['id'] == '') ||
        ((userInfo['avatar'] as String).isEmpty &&
            (userInfo['nickName'] as String).isEmpty &&
            (userInfo['id'] as String).isEmpty) ||
        (userInfo['avatar'] == null ||
            userInfo['nickName'] == null ||
            userInfo['id'] == null)) {
      return Image.asset(
        'assets/images/avatar_1.jpg',
        width: 50,
        height: 50,
      );
    }
    if (!kIsWeb && (userInfo['avatar'] as String).startsWith('/data')) {
      return Image.file(
        File(userInfo['avatar']),
        width: 50,
        height: 50,
      );
    } else if ((userInfo['avatar'] as String).startsWith('http')) {
      return Image.network(
        userInfo['avatar'],
        width: 50,
        height: 50,
      );
    } else {
      return Image.asset(
        'assets/images/avatar_1.jpg',
        width: 50,
        height: 50,
      );
    }
  }

  Widget _getRow() {
    return Container(
      padding: const EdgeInsets.all(10),
      // color: Colors.blue,
      child: Row(children: [
        ClipRRect(
            borderRadius: BorderRadius.circular(100),
            child: SizedBox(
              width: 50,
              height: 50,
              child: getImg(),
            )),
        const SizedBox(
          width: 10,
        ),
        Text(
          userInfo['nickName'] != null && userInfo['nickName'] != ''
              ? userInfo['nickName']
              : '游客',
          style: const TextStyle(fontSize: 16, color: Colors.white),
        ),
        const Spacer(),
        TextButton(
          onPressed: () {
            Navigator.pushNamed(context, 'profile', arguments: userInfo);
          },
          child: const Text(
            "去完善信息",
            style: TextStyle(fontSize: 14, color: Colors.white),
          ),
        ),
        const Icon(
          Icons.arrow_forward_ios,
          size: 14,
          color: Colors.white,
        ),
      ]),
    );
  }

  final List menuList = [
    {
      "title": "我的房屋",
      "icon": "assets/images/house_profile_icon@2x.png",
    },
    {
      "title": "我的报修",
      "icon": "assets/images/repair_profile_icon@2x.png",
    },
    {
      "title": "访客记录",
      "icon": "assets/images/visitor_profile_icon@2x.png",
    }
  ];
  List<Widget> _getColum() {
    return menuList.map((item) {
      return SizedBox(
        height: 40,
        child: Row(
          children: [
            Image.asset(
              item['icon'],
              width: 16,
            ),
            const SizedBox(
              width: 10,
            ),
            Text(item['title']),
            const Spacer(),
            const Icon(
              Icons.arrow_forward_ios,
              size: 14,
              color: Colors.grey,
            ),
          ],
        ),
      );
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(200, 85, 145, 175),
      appBar: AppBar(
        title: const Text('我的'),
        centerTitle: true,
        elevation: 0,
        backgroundColor: Colors.transparent,
      ),
      body: ListView(children: [
        _getRow(),
        Container(
          margin: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
          padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(10)),
          child: Column(
            children: _getColum(),
          ),
        ),
        TextButton(
            onPressed: () {
              showDialog(
                  context: context,
                  builder: (BuildContext ctx) {
                    return AlertDialog(
                      title: const Text('提示'),
                      content: const Text('确定退出吗'),
                      actions: [
                        TextButton(
                            onPressed: () {
                              Navigator.pop(context);
                            },
                            child: const Text('取消')),
                        TextButton(
                            onPressed: () {
                              tokenManager.removePre();
                              Navigator.pop(context);
                              widget.toIndex(0);
                            },
                            child: const Text('确定')),
                      ],
                    );
                  });
            },
            child: const Text(
              '退出',
              style: TextStyle(color: Colors.white),
            )),
      ]),
    );
  }
}
